<template>
  <!-- 窗口内容 -->
  <a-modal
    :open="props.modelVisible"
    title="新建分配"
    ok-text="确认"
    cancel-text="取消"
    @ok="onOk"
    @cancel="
      formRef.resetFields();
      emit('update:modelVisible', false);
    "
    :maskClosable="true"
  >
    <!-- 表单内容 -->
    <a-form
      ref="formRef"
      :model="formState"
      name="form_in_modal"
      :label-col="{ style: { width: '90px' } }"
      AutoComplete="off"
    >
      <a-form-item
        name="classId"
        label="选择班级"
        :rules="[{ required: true, message: '班级不能为空', trigger: 'blur' }]"
      >
        <a-select
          v-model:value="formState.classId"
          placeholder="请选择班级"
          :field-names="{ label: 'className', value: 'classId' }"
          :options="classes"
          @change="selectClass"
          :listHeight="150"
        />
      </a-form-item>
      <a-form-item
        name="teamId"
        label="选择小组"
        :rules="[{ required: true, message: '小组不能为空', trigger: 'blur' }]"
      >
        <a-select
          v-model:value="formState.teamId"
          placeholder="请选择承担小组"
          :field-names="{ label: 'teamName', value: 'teamId' }"
          :options="teams"
          @change="changeMembers"
          :listHeight="150"
        />
      </a-form-item>
      <a-form-item 
        name="userList" 
        label="承担对象" 
        :rules="[{ required: hasMembers, message: '承担对象不能为空', trigger: 'blur' }]"
      >
        <a-select
          v-model:value="formState.userList"
          mode="multiple"
          placeholder="请选择承担对象"
          :showSearch="true"
          optionFilterProp="label"
          :disabled="items.length === 0"
          :field-names="{ value: 'userId', label: 'userName' }"
          :options="items"
          style="width: 100%"
          :listHeight="180"
          :maxTagCount="3"
          :maxTagTextLength="5"
        >
          <template #tagRender="{ label, onClose, value }">
            <a-tag
              closable
              @close="onClose"
              style="margin-right: 3px"
            >
              {{ label }}
            </a-tag>
          </template>
        </a-select>
        <div v-if="items.length === 0" style="color: #ff4d4f;">该小组暂无成员，仅分配给小组</div>
        <div v-else-if="formState.userList && formState.userList.length > 0" style="color: #52c41a; margin-top: 4px;">
          已选择 {{ formState.userList.length }} 名学生
        </div>
      </a-form-item>
      <a-form-item
        name="endTime"
        label="截至时间"
        :rules="[{ required: true, message: '截至时间不能为空', trigger: 'blur' }]"
      >
        <a-date-picker v-model:value="formState.endTime" style="width: 100%" show-time />
      </a-form-item>
      
      <a-form-item name="attachments" label="附件">
        <div style="min-height: 100px;">
          <a-upload
            v-model:file-list="fileList"
            :customRequest="uploadAttachment"
            multiple
            :showUploadList="true"
            name="file"
          >
            <a-button type="primary">
              <upload-outlined></upload-outlined>
              上传附件
            </a-button>
          </a-upload>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue';
import { reactive, ref, toRaw, computed } from 'vue';
import type { FormInstance, UploadChangeParam, UploadProps } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import type { UnwrapRef } from 'vue';
import TaskDao from '@/daos/task_dao';
import ClassDao from '@/daos/class_dao';
import ProjectDao from '@/daos/project_dao';
import AttachmentDao from '@/daos/attachment_dao';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import { UploadOutlined } from '@ant-design/icons-vue';

const store = useStore();

const projectDao = new ProjectDao();
const taskDao = new TaskDao();
const classDao = new ClassDao();
const attachmentDao = new AttachmentDao();

//接口定义
interface FormState {
  userList: []; //用户列表
  taskId: number; //项目id
  classId: number;
  creatorId: number; //创建者id
  createTime: dayjs.Dayjs; //创建时间
  endTime: dayjs.Dayjs; //截止时间
  teamId: number; //小组id
}

//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  //任务ID，用于选择任务
  taskId: {
    type: Number,
    defalt: null
  }
});
//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);
//普通项目成员列表
const items = ref([]);
//班级列表
const classes = ref([]);
//小组列表
const teams = ref([]);
//定义表单
const formRef = ref<FormInstance>();

// 计算当前选中的小组是否有成员
const hasMembers = computed(() => {
  return items.value && items.value.length > 0;
});

//根据选中的小组id 获取对应的成员
const changeMembers = (teamId) => {
  console.log('正在获取小组ID为', teamId, '的成员');
  
  // 清空用户选择
  formState.userList = [];
  
  if (!teamId) {
    items.value = [];
    return;
  }
  
  // 直接从后端获取小组成员
  projectDao
    .getStudentsByTeamId(teamId)
    .then((result) => {
      console.log('从API获取到的小组成员:', result.data);
      if (result.data && result.data.code === 200 && result.data.data && result.data.data.length > 0) {
        // 确保数据格式正确并且去重
        const uniqueStudents = {};
        result.data.data.forEach(student => {
          // 使用userId作为键，避免重复
          if (!uniqueStudents[student.userId]) {
            uniqueStudents[student.userId] = {
              userId: student.userId,
              userName: student.userName || '未知学生'
            };
          }
        });
        
        // 转换回数组
        const members = Object.values(uniqueStudents);
        console.log('处理后的小组成员:', members);
        items.value = members;
      } else {
        console.log('该小组没有成员或返回数据格式不正确');
        items.value = [];
      }
    })
    .catch((error) => {
      console.error('获取小组成员错误', error);
      items.value = [];
    });
};

//初始表单内容全为undefined
const formState: UnwrapRef<FormState> = reactive({
  userList: undefined,
  classId: undefined,
  teamId: undefined,
  taskId: undefined,
  endTime: undefined,
  createTime: undefined,
  creatorId: store.getters.userId
});

//查询项目成员
const findMumber = () => {
  projectDao
    .findProjectTeamsAndMembersByProjectId(null, formState.teamId)
    .then((result) => {
      teams.value = result.data.data;
    })
    .catch((error) => {
      console.error('findTeamsAndMembers 错误', error);
    });
};

//获取班级信息
const findClass = () => {
  return classDao.findClassByCourseId(store.getters.courseId).then((result) => {
    console.log(result);

    classes.value = result.data.data; // 直接替换整个数组
  });
};
//选择班级后获取小组信息
const selectClass = (value) => {
  teams.value = classes.value.find((item) => item.classId == value).teamList;
  // 清空小组选择和成员列表
  formState.teamId = undefined;
  formState.userList = undefined;
  items.value = [];
};

const onOk = () => {
  formRef.value
    .validateFields()
    .then(() => {
      //请求后端
      formState.createTime = dayjs();
      
      // 如果没有成员，设置userList为空数组
      if (!hasMembers.value) {
        formState.userList = [];
      }
      
      taskDao
        .addAssignmentAndUndertaker(toRaw(formState))
        .then((result) => {
          message.success(result.data.msg);
          //更新任务页面内容
          emit('confirm');
          //更新窗口状态，false为关闭
          emit('update:modelVisible', false);
          //清空表单内容
          formRef.value.resetFields();
        })
        .catch((error) => {
          console.error('创建任务分配失败 addAssignmentAndUndertaker', error);
        });
    })
    .catch((error) => {
      console.log('数据验证失败:', error);
    });
};

//文件上传相关
const fileList = ref([]);
const attachmentData = ref([]);

// 获取附件列表
const findAttachments = async () => {
  if (props.taskId) {
    try {
      const result = await attachmentDao.findAttachmentsByTaskId(props.taskId);
      if (result.data && result.data.data) {
        attachmentData.value = result.data.data;
      }
    } catch (error) {
      console.error('获取附件列表失败', error);
    }
  }
};

// 上传附件
const uploadAttachment = async (options) => {
  try {
    if (!props.taskId) {
      message.error('请先创建任务');
      options.onError('任务ID不存在');
      return;
    }
    
    message.loading({ content: '正在上传...', key: 'uploading' });
    
    const result = await attachmentDao.upLoadTaskAttachment(
      options.file,
      props.taskId,
      store.getters.userId
    );
    
    if (result.data && result.data.code === 200) {
      message.success({ content: '上传成功', key: 'uploading' });
      options.onSuccess(result, options.file);
      
      // 重新获取附件列表
      await findAttachments();
    } else {
      message.error({ content: result.data?.msg || '上传失败', key: 'uploading' });
      options.onError(new Error(result.data?.msg || '上传失败'));
    }
  } catch (error) {
    console.error('上传附件失败', error);
    message.error({ content: '上传失败: ' + (error.message || '未知错误'), key: 'uploading' });
    options.onError(error);
  }
};

// 格式化文件大小
const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};

watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue === true) {
      formState.taskId = props.taskId;
      findClass();
      findMumber();
      
      // 加载任务附件
      if (props.taskId) {
        findAttachments();
      }
    }
  }
);
</script>
<style scoped></style>
